import axios from 'axios'
import fileDownload from 'js-file-download'
import store from '@/store'
import { getAccessToken } from '@/utils/auth'
import { matchContentDispositionFilename } from '@/utils'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: process.env.VUE_APP_REQUEST_DOWNLOAD_TIMEOUT // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers.Authorization = 'Bearer ' + getAccessToken()
    }
    console.log('request:', config)
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

export default async function download(path, data) {
  const res = await service({
    url: path,
    method: 'POST',
    data: data,
    responseType: 'blob'
  })
  console.log('res', res)
  const filename = matchContentDispositionFilename(res.headers)
  console.log(filename)
  // const disposition = res.headers['content-disposition']
  // const filename = decodeURI(disposition.replace('attachment;filename=', ''))
  // const fileType = res.headers['content-type']

  const resBlob = res.data
  const resData = null
  try {
    await new Promise((resolve, reject) => {
      // 通过 FileReader 接受并解析
      const reader = new FileReader()
      reader.addEventListener('abort', reject)
      reader.addEventListener('error', reject)
      reader.addEventListener('loadend', () => {
        resolve(reader.result)
      })
      // 文件
      reader.readAsText(resBlob)
    })
    // resData = JSON.parse(resText)
  } catch (err) {
    console.log(err)
  }
  if (resData) {
    console.log(resData)
    // if (resData.error) {
    // } else {
    // }
    fileDownload(resData, filename)
  } else {
    fileDownload(resBlob, filename)
  }
}
